package com.anbinh.doctor;

import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.anbinh.doctor.fragment.FragmentLogin;
import com.anbinh.doctor.fragment.account.FragmentAccount;
import com.anbinh.doctor.fragment.benhnhan.FragmentListPatients;
import com.anbinh.doctor.fragment.lichhen.FragmentLichhen;
import com.anbinh.doctor.fragment.lichkham.FragmentLichkham;
import com.anbinh.doctor.fragment.tinnhan.FragmentMessages;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.utils.IRcallBak;
import com.anbinh.doctor.utils.TabType;
import com.anbinh.doctor.utils.Utils;

public class MainActivity extends SherlockFragmentActivity implements
		IRcallBak, SearchView.OnQueryTextListener,
		SearchView.OnSuggestionListener {
	public static Activity mActivity;
	private TextView mTitle;
	private View lineTitle;
	private int mPositionPage = -1;// TabType.LICHHEN.getCode();
	private ImageView mDropIcon;
	private static boolean isActive = true;
	private static boolean isShowDeleteLK = false;

	private int ONSTOP = 1;
	private int ONSTART = 2;
	private int ADD = 3;
	private int SEND_ALL = 4;
	private SearchView searchView;
	private SuggestionsAdapter adpaterSearchMessage = null;
	private UserLogin userLogin;
	private ActionMode mMode;
	private static final String[] COLUMNS = { BaseColumns._ID,
			SearchManager.SUGGEST_COLUMN_TEXT_1, };

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mActivity = MainActivity.this;
		getSupportActionBar().setDisplayOptions(
				ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
		getSupportActionBar().setCustomView(R.layout.taskbar);

		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(true);
		getSupportActionBar().setTitle(" ");
		mDropIcon = (ImageView) findViewById(R.id.icDrop);
		mTitle = (TextView) findViewById(R.id.lblChuyenKhoaName);

		userLogin = Utils.getAccountModel(MainActivity.this, Utils.KEY_USER);

		getSupportFragmentManager()
				.beginTransaction()
				.replace(R.id.fragment_container, FragmentLogin.newInstance(),
						"TAG_MAIN").addToBackStack(null).commit();

		mTitle.setText(String.format(getResources().getString(R.string.thang),
				Utils.getCurrentMonth()));

		lineTitle = (View) findViewById(R.id.lineTitle);
		lineTitle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mPositionPage == TabType.LICHHEN.getCode()
						|| mPositionPage == TabType.LICHKHAM.getCode()) {
					Bundle bundle = new Bundle();
					bundle.putInt(Utils.KEY, Utils.LICHHEN_SELECT_MONTH);
					bundle.putString(Utils.TITLE,
							getResources().getString(R.string.chon_thang));
					bundle.putInt(Utils.REQUEST_CODE, mPositionPage);
					Utils.getNewIntent(MainActivity.this, bundle);
				}
			}
		});
		getSupportActionBar().setIcon(
				getResources().getDrawable(R.drawable.ic_tranparesnt));
		lineTitle.setVisibility(View.GONE);

	}

	@Override
	public void onBackPressed() {
		finish();
		System.exit(0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (data == null)
			return;
		if (requestCode == Utils.ADD_PATIENT) {
			FragmentListPatients.newInstance().onResetData();
			FragmentListPatients.newInstance().onLoadData();
			return;
		}
		if (requestCode == Utils.CREATE_LH) {
			FragmentLichkham.newInstance().onloadData();
			return;
		}
		if (requestCode == Utils.ONRESUME_LICHHEN) {
			FragmentLichhen.newInstance().onLoadData();
			return;
		}

		if (requestCode == Utils.REQ_EDIT_AVATAR) {
			FragmentAccount.newInstance().updateInfo(data);
			return;
		}

		if (requestCode == TabType.LICHHEN.getCode()) {
			if (resultCode == Activity.RESULT_OK) {
				mTitle.setText(String.format(
						getResources().getString(R.string.thang),
						data.getStringExtra(Utils.TIME)));
				int selectMonth = Integer.parseInt(data
						.getStringExtra(Utils.TIME));
				if (selectMonth == Integer.parseInt(Utils.getCurrentMonth())) {
					FragmentLichhen.newInstance().onDisplayTime(selectMonth,
							Integer.parseInt(Utils.getCurrentDay()) - 1);
				} else {
					FragmentLichhen.newInstance().onDisplayTime(selectMonth, 0);
				}

			}
		} else if (requestCode == TabType.LICHKHAM.getCode()) {
			if (resultCode == Activity.RESULT_OK) {
				mTitle.setText(String.format(
						getResources().getString(R.string.thang),
						data.getStringExtra(Utils.TIME)));

				int selectMonth = Integer.parseInt(data
						.getStringExtra(Utils.TIME));
				if (selectMonth == Integer.parseInt(Utils.getCurrentMonth())) {
					FragmentLichkham.newInstance().onDisplayTime(selectMonth,
							Integer.parseInt(Utils.getCurrentDay()) - 1);
				} else {
					FragmentLichkham.newInstance()
							.onDisplayTime(selectMonth, 0);
				}

			}
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		mDropIcon.setVisibility(View.GONE);
		switch (mPositionPage) {
		case -1:

			break;
		case 0:
			if (isActive) {
				changeTaskbar(ONSTART, String.format(
						getResources().getString(R.string.thang),
						Utils.getCurrentMonth()));
			} else {
				changeTaskbar(ONSTOP, String.format(
						getResources().getString(R.string.thang),
						Utils.getCurrentMonth()));

			}
			mDropIcon.setVisibility(View.VISIBLE);

			searchView = new SearchView(getSupportActionBar()
					.getThemedContext());
			searchView.setQueryHint("Tên bệnh nhân hoặc mã cuộc hẹn");
			searchView.setOnQueryTextListener(this);
			searchView.setOnSuggestionListener(this);

			menu.add(1, Utils.SEARCH_LICH_HEN, Menu.NONE, "Tìm kiếm")
					.setIcon(R.drawable.ic_search)
					.setActionView(searchView)
					.setShowAsAction(
							MenuItem.SHOW_AS_ACTION_IF_ROOM
									| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
			setStyleSearch();
			break;
		case 1:
			mDropIcon.setVisibility(View.VISIBLE);
			changeTaskbar(ADD, String.format(
					getResources().getString(R.string.thang),
					Utils.getCurrentMonth()));
			menu.add(0, R.id.delete_lich_kham, Menu.NONE, "Tạo lịch hẹn")
					.setIcon(R.drawable.ic_edit)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			break;
		case 2:
			changeTaskbar(SEND_ALL, "Tin nhắn");
			searchView = new SearchView(getSupportActionBar()
					.getThemedContext());
			searchView.setQueryHint("Tên bệnh nhân");
			searchView.setOnQueryTextListener(this);
			searchView.setOnSuggestionListener(this);

			menu.add(1, Utils.SEARCH_LICH_HEN, Menu.NONE, "Tìm kiếm")
					.setIcon(R.drawable.ic_search)
					.setActionView(searchView)
					.setShowAsAction(
							MenuItem.SHOW_AS_ACTION_IF_ROOM
									| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
			setStyleSearch();
			break;

		case 3:
			changeTaskbar(ADD, "Bệnh nhân");
			searchView = new SearchView(getSupportActionBar()
					.getThemedContext());
			searchView.setQueryHint("Tên bệnh nhân");
			searchView.setOnQueryTextListener(this);
			searchView.setOnSuggestionListener(this);

			searchView.setSuggestionsAdapter(adpaterSearchMessage);
			menu.add(1, Utils.SEARCH_PATIENTS, Menu.NONE, "Tìm kiếm")
					.setIcon(R.drawable.ic_search)
					.setActionView(searchView)
					.setShowAsAction(
							MenuItem.SHOW_AS_ACTION_IF_ROOM
									| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
			setStyleSearch();
			break;
		case 4:
			changeTaskbar(-1, "Tài khoản");
			menu.add(0, Utils.ACCOUNT, Menu.NONE, "None")
					.setIcon(R.drawable.ic_tranparesnt)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			break;

		}
		return super.onCreateOptionsMenu(menu);
	}

	public void setStyleSearch() {
		AutoCompleteTextView searchText = (AutoCompleteTextView) searchView
				.findViewById(R.id.abs__search_src_text);
		searchText.setHintTextColor(getResources().getColor(
				android.R.color.white));
		searchText.setTextColor(getResources().getColor(android.R.color.white));
		searchText.setTextSize(14);
	}

	private class SuggestionsAdapter extends CursorAdapter {
		View view;

		public SuggestionsAdapter(Context context, Cursor c) {
			super(context, c, 0);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(context);
			view = inflater.inflate(R.layout.item_search_lich_hen, parent,
					false);
			return view;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView tv = (TextView) view.findViewById(R.id.lblName);
			final int textIndex = cursor
					.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1);
			tv.setText(cursor.getString(textIndex));
		}
	}

	public void changeTaskbar(int option, String title) {
		if (option == ONSTART) {
			getSupportActionBar().setIcon(
					getResources().getDrawable(R.drawable.ic_nonotification));
		} else if (option == ONSTOP) {
			getSupportActionBar().setIcon(
					getResources().getDrawable(R.drawable.ic_nonotification));
		} else if (option == ADD) {
			getSupportActionBar().setIcon(
					getResources().getDrawable(R.drawable.ic_add));
		} else if (option == SEND_ALL) {
			getSupportActionBar().setIcon(
					getResources().getDrawable(R.drawable.ic_send_messages));
		} else {
			getSupportActionBar().setIcon(
					getResources().getDrawable(R.drawable.ic_tranparesnt));
		}
		mTitle.setText(title);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Bundle bundle = new Bundle();
		switch (item.getItemId()) {
		case R.id.delete_lich_kham:
			if (isShowDeleteLK) {
				isShowDeleteLK = false;
			} else {
				isShowDeleteLK = true;
			}
			FragmentLichkham.newInstance().onShowDelete(isShowDeleteLK);

			break;
		case android.R.id.home:
			if (mPositionPage == TabType.LICHHEN.getCode()) {
				isActive = !isActive;
				if (!FragmentLichhen.newInstance().isCheckAppoitmentExist()) {
					Utils.showMessage(MainActivity.this, getResources()
							.getString(R.string.hom_nay_ban_khong_co_lich));
				} else if (!Utils.isCheckPassDay(FragmentLichhen.newInstance()
						.getCurrentDay())) {
					Utils.showMessage(MainActivity.this, getResources()
							.getString(R.string.lich_da_qua));
				} else {
					bundle.putInt(Utils.KEY, Utils.TAM_HOAN);
					bundle.putString(Utils.TITLE,
							getResources().getString(R.string.tam_dung_kham));
					bundle.putInt(Utils.REQUEST_CODE, Utils.ONRESUME_LICHHEN);
					Utils.getNewIntent(MainActivity.this, bundle);
				}
			} else if (mPositionPage == TabType.LICHKHAM.getCode()) {// tao lich
																		// kham
				bundle.putInt(Utils.KEY, R.id.tao_lich_kham);
				bundle.putString(Utils.TITLE,
						getResources().getString(R.string.them_lich_kham));
				bundle.putInt(Utils.REQUEST_CODE, Utils.CREATE_LH);
				bundle.putBoolean(Utils.CUSTOMBAR, true);
				Utils.getNewIntent(MainActivity.this, bundle);
			} else if (mPositionPage == TabType.BENHNHAN.getCode()) {
				bundle.putInt(Utils.KEY, Utils.ADD_PATIENT);
				bundle.putInt(Utils.REQUEST_CODE, Utils.ADD_PATIENT);
				bundle.putString(Utils.TITLE,
						getResources().getString(R.string.them_benh_nhan));
				bundle.putBoolean(Utils.CUSTOMBAR, true);
				Utils.getNewIntent(MainActivity.this, bundle);
			} else if (mPositionPage == TabType.TINNHAN.getCode()) {
				bundle.putInt(Utils.KEY, R.id.send_message);
				bundle.putInt(Utils.REQUEST_CODE, Utils.SEND_MESSAGES);
				bundle.putString(Utils.TITLE,
						getResources().getString(R.string.gui_tin_nhan));
				bundle.putBoolean(Utils.CUSTOMBAR, false);
				Utils.getNewIntent(MainActivity.this, bundle);
			}

			break;
		default:
			break;
		}

		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onSuggestionSelect(int position) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onSuggestionClick(int position) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		if (query.isEmpty())
			return false;
		Bundle bundle = new Bundle();
		bundle.putBoolean(Utils.CUSTOMBAR, false);
		bundle.putString(Utils.TITLE, "Tìm kiếm '" + query + "'");
		bundle.putString(Utils.KEY_SEARCH, query);

		if (mPositionPage == TabType.LICHHEN.getCode()) {
			bundle.putInt(Utils.KEY, Utils.SEARCH_LICH_HEN);
			Utils.getNewIntent(MainActivity.this, bundle);
		} else if (mPositionPage == TabType.BENHNHAN.getCode()) {
			bundle.putInt(Utils.KEY, Utils.SEARCH_BENH_NHAN);
			bundle.putBoolean(Utils.KEY_IS_SEARCH, true);
			Utils.getNewIntent(MainActivity.this, bundle);
		} else {
			bundle.putInt(Utils.KEY, Utils.SEARCH_MESSAGE);
			Utils.getNewIntent(MainActivity.this, bundle);
		}

		return false;
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		if (mPositionPage == TabType.TINNHAN.getCode())
			onSearch(newText);
		return false;
	}

	private void onSearch(String newText) {
	}

	@Override
	public void onDisplay(int type, Bundle data) {
		mPositionPage = type;
		switch (type) {
		case Utils.LOGIN_FORM:
			getSupportActionBar().setIcon(
					getResources().getDrawable(R.drawable.ic_tranparesnt));
			lineTitle.setVisibility(View.GONE);
			invalidateOptionsMenu();
			break;
		case Utils.DELETE_MESSAGE:
			mMode = startActionMode(new AnActionModeOfEpicProportions(
					Utils.DELETE_MESSAGE));
			break;
		case Utils.DELETE_PATIENTS:
			mMode = startActionMode(new AnActionModeOfEpicProportions(
					Utils.DELETE_PATIENTS));
			break;
		default:
			if (mMode != null)
				mMode.finish();
			lineTitle.setVisibility(View.VISIBLE);

			invalidateOptionsMenu();
			break;
		}
	}

	private final class AnActionModeOfEpicProportions implements
			ActionMode.Callback {
		private int mOption;

		public AnActionModeOfEpicProportions(int option) {
			this.mOption = option;
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			menu.add("Save").setIcon(R.drawable.ic_delete_black_24dp)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;

		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			if (mOption == Utils.DELETE_MESSAGE) {
				FragmentMessages.newInstance().onDelete();
			} else if (mOption == Utils.DELETE_PATIENTS) {
				FragmentListPatients.newInstance().onDelete();
			}
			mode.finish();
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			FragmentMessages.newInstance().setLongclick(false);
			FragmentListPatients.newInstance().setLongclick(false);

		}
	}
}
